import { history } from 'umi';
import { PageMetaConfig } from './interface';
import { useCallback, useEffect, useState } from 'react';
import { accountDetail } from './api';
import { initialSchema, initialSchemaType } from '@/components/schema-form-render/utils';
import { ISchema } from '@formily/react';

import { cloneDeep } from 'lodash';

interface GetAccountDetail {
  initLoading: boolean;
  jsonSchema: ISchema;
  operationButton: any[];
}

export const useBackList = () => {
  return () => {
    history.push(PageMetaConfig.LIST_LINK);
  };
};

export const useGetAccountDetail = (
  id: string,
  pageCode: PageMetaConfig.EDIT | PageMetaConfig.DETAIL,
  type: initialSchemaType,
): GetAccountDetail => {
  const [loading, setLoading] = useState(false);
  const [jsonSchema, setJsonSchema] = useState({});
  const [operationButton, setOperationButton] = useState([]);

  const fetchDetail = useCallback(
    (params) => {
      setLoading(true);

      accountDetail(params)
        .then((res: any) => {
          const { result } = res;

          const { schema, buttons } = initialSchema(cloneDeep(result), type) as any;
          setOperationButton(buttons || []);
          setJsonSchema(schema);
        })
        .finally(() => {
          setLoading(false);
        });
    },
    [type],
  );

  useEffect(() => {
    if (id && pageCode) {
      fetchDetail({
        id,
        pageCode,
      });
    }
  }, [id, pageCode]);

  return {
    initLoading: loading,
    jsonSchema,
    operationButton,
  };
};
